﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.RoleMenu;
using B.S.BasicData.Api.Read.DTO;
using B.S.BasicData.Domian.Entities.Menu;
using B.S.BasicData.Domian.Entities.RBAC;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System.Data;

namespace B.S.BasicData.Api.Read.Application.Handler.RoleMenu
{
    public class RoleMenuTreeHandler : IRequestHandler<RoleMenuTreeCommand, ApiResult<List<RoleMenuTreeDTO>>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public RoleMenuTreeHandler(IBaseRepository<MenuModel>menuRepo,IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<List<RoleMenuTreeDTO>>> Handle(RoleMenuTreeCommand request, CancellationToken cancellationToken)
        {
            var res=new ApiResult<List<RoleMenuTreeDTO>>();
            List<RoleMenuTreeDTO>list=new List<RoleMenuTreeDTO>();
            var allllist=menuRepo.GetAll().ToList();
            var toplist = allllist.Where(x => x.Pid == 0);
            foreach (var item in toplist)
            {
                RoleMenuTreeDTO dto = new RoleMenuTreeDTO();
                dto.value = item.Id;
                dto.laber=item.MenuName;
                GaetTree(allllist, dto);
                list.Add(dto);
            }
          
            res.Data = list;
            return Task.FromResult(res);
        }

        private void GaetTree(List<MenuModel> allllist, RoleMenuTreeDTO tree)
        {
           var list=allllist.Where(x => x.Pid == tree.value);
            foreach (var item in list)
            {
                RoleMenuTreeDTO dtos = new RoleMenuTreeDTO()
                {
                    value = item.Id,
                    laber=item.MenuName,
                };
                tree.Children.Add(dtos);
                GaetTree(allllist, dtos);
            }
        }
    }
}
